<template>
	<!-- 添加过渡层 -->
	<view class="popup-mask" :class="{ 'mask-show': show }" @touchmove.stop.prevent>
		<view class="popup-container" :class="{ 'popup-show': show }">
			<view class="popup-content">
				<!-- 弹窗内容保持不变 -->
				<view class="popup-header">
					<text class="title">请选择购买方式</text>
					<!-- 关闭按钮 -->
					<uni-icons type="closeempty" size="24" color="#33333" @click="closePopup"></uni-icons>
				</view>
				<view class="popup-body">
					<!-- 服务规格选择 -->
					<view class="section2">
						<text class="section-title">服务规格</text>
						<view class="options2">
							<view v-for="(service, index) in serviceOptions" :key="index" class="option2"
								:class="{ active: selectedService === service.id }"
								@click.stop="selectService(service.id)">
								<view class="option-box">
									<text>{{ service.specsName }}</text>
									<image v-if="service.recommended" :src="`${$ImgBaseUrl}recommend.png`"
										class="recommended" />
									<!-- 服务规格价格默认展示 -->
									<!-- <text class="price" :class="{ 'active-price': selectedService === service.id }">
										{{ getServicePrice(service.id) }}
									</text> -->
								</view>
								<view class="ProductSpecification-box">
									<text class="ProductSpecification-text">{{service.remark}}</text>
								</view>
							</view>
						</view>
					</view>
					<!-- 房屋面积选择（添加价格展示） -->
					<view class="section">
						<text class="section-title">规格选项</text>
						<view class="options">
							<view v-for="(area, index) in filteredAreaOptions" :key="index" class="option"
								:class="{ active: selectedArea === area.id }" @click.stop="selectArea(area.id)">
								<view class="option-info">
									<text class="area-name">{{ area.priceParamName }}</text>
									<!-- 新增价格展示区域 -->
									<view class="price-group">
										<text class="preferential-price">￥{{ area.preferentialPrice }}</text>
										<text class="original-price" v-if="area.preferentialPrice < area.priceAmount">
											￥{{ area.priceAmount }}
										</text>
									</view>
								</view>
							</view>
						</view>
					</view>

				</view>
				<view class="popup-footer">
					<button class="add-to-cart" @click.stop="addToCart">加入购物车</button>
					<button class="order-now" @click.stop="orderNow">立即下单</button>
				</view>
			</view>
		</view>
	</view>
</template>


<script setup>
	import {
		addCartShopping
	} from "@/api/cart.js";
	import {
		platformCreate
	} from "@/api/consumerOrder.js";
	import {
		ref,
		watch
	} from "vue";
	import {
		useCartStore
	} from '@/store/cart.js'
	const cartStore = useCartStore()
	import {
		queryCartList
	} from "@/api/cart.js";

	// 控制弹窗显示隐藏
	const show = ref(false);
	const currentCouponId = ref('')
	const props = defineProps({
		detailData: {
			type: Object,
			default: () => ({})
		},
		couponId: { // 新增 couponId 属性
			type: String,
			default: ''
		}
	});

	// 房屋面积选项（原始数据）
	const areaOptions = ref([]);
	// 服务规格选项
	const serviceOptions = ref([]);

	// 选中的房屋面积和服务规格
	const selectedService = ref(""); // 服务规格id
	const selectedArea = ref(""); // 房屋面积id

	// 过滤后的房屋面积（与当前服务规格匹配）
	const filteredAreaOptions = ref([]);

	// 打开弹窗时初始化数据
	const openPopup = (data, couponId) => {
		show.value = true;
		serviceOptions.value = data.itemParamList || []; // 服务规格数据
		areaOptions.value = data.itemPriceList || []; // 房屋面积原始数据
		// 初始化：默认选中第一个推荐的服务规格（无推荐则选第一个）
		if (serviceOptions.value.length > 0) {
			const recommended = serviceOptions.value.find((item) => item.recommended);
			selectedService.value = recommended ? recommended.id : serviceOptions.value[0].id;
		}
		// 保存 couponId 到组件内部
		currentCouponId.value = couponId;
	};

	// 关闭弹窗
	const closePopup = () => {
		show.value = false;
	};

	// 监听服务规格变化，联动房屋面积
	watch(
		() => selectedService.value,
		(newServiceId) => {
			if (!newServiceId) return;

			// 筛选出localParamId与服务规格id匹配的房屋面积
			filteredAreaOptions.value = areaOptions.value.filter((area) => area.localParamId === newServiceId);

			// 自动选中第一个匹配的房屋面积
			if (filteredAreaOptions.value.length > 0) {
				selectedArea.value = filteredAreaOptions.value[0].id;
			} else {
				selectedArea.value = ""; // 无匹配项时清空
			}
		}, {
			immediate: true
		} // 初始化时立即执行
	);

	// 获取服务规格对应的价格
	const getServicePrice = (serviceId) => {
		if (!selectedArea.value) return "0";

		// 找到当前服务规格下选中的房屋面积对应的价格
		const area = areaOptions.value.find((item) => item.id === selectedArea.value && item.localParamId ===
			serviceId);

		return area ? "￥" + area.preferentialPrice : "";
	};

	// 选择服务规格
	const selectService = (serviceId) => {
		selectedService.value = serviceId;
	};

	// 选择房屋面积
	const selectArea = (areaId) => {
		selectedArea.value = areaId;
	};

	// 加入购物车
	const addToCart = async () => {
		closePopup();
		try {
			const res = await addCartShopping({
				quantity: 1,
				localPriceId: selectedArea.value
			});
			if (res.code === 200) {
				uni.showToast({
					title: "加入购物车成功",
					icon: "success"
				});
				// 重新查询最新数量
				const cartRes = await queryCartList({
					pageNum: 1,
					pageSize: 9999
				});
				cartStore.updateCartCount(cartRes.rows.length);
			}
		} catch (error) {
			console.error("加入购物车失败:", error);
			uni.showToast({
				title: '加入购物车失败',
				icon: "error"
			});
		}
	};

	// 立即下单
	const orderNow = () => {
		console.log("立即下单", {
			selectedArea: selectedArea.value,
			selectedService: selectedService.value,
			couponId: currentCouponId.value
		});
		platformCreate({
			priceIds: [selectedArea.value]
		}).then((res) => {
			if (res.code === 200) {
				uni.showToast({
					title: "下单成功",
					icon: "success"
				});
				closePopup();

				uni.navigateTo({
					url: `/pages/order/consumerOrder/placeOrder?id=${res.data.id}&couponId=${currentCouponId.value}`
				});
			} else {
				uni.showToast({
					title: "下单失败",
					icon: "error"
				});
			}
		});
	};

	// 暴露方法给父组件
	defineExpose({
		openPopup
	});
</script>

<style scoped lang="scss">
	/* 遮罩层样式 */
	.popup-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0);
		display: flex;
		justify-content: center;
		align-items: flex-end;
		z-index: 999;
		transition: background-color 0.3s ease;
		pointer-events: none;

		&.mask-show {
			background-color: rgba(0, 0, 0, 0.5);
			pointer-events: auto;
		}
	}

	/* 容器样式 */
	.popup-container {
		width: 95%;
		max-height: 80vh;
		transform: translateY(100%);
		transition: transform 0.3s ease;
		margin-bottom: 10rpx;

		&.popup-show {
			transform: translateY(0);
		}
	}

	/* 内容区域样式 */
	.popup-content {
		background-color: white;
		border-radius: 20rpx 20rpx 0 0;
		width: 100%;
		max-height: 80vh;
		overflow: hidden;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
	}

	/* 头部样式 */
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;

		.title {
			font-size: 34rpx;
			font-weight: 500;
			color: #333333;
		}
	}

	/* 身体区域样式 */
	.popup-body {
		padding: 30rpx;
	}

	/* 规格选项样式 */
	.section {
		margin-bottom: 30rpx;

		.section-title {
			font-weight: 400;
			color: #666;
			font-size: 30rpx;
		}
	}

	.options {
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;
	}

	.option {
		padding: 16rpx 30rpx;
		border-radius: 10rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		cursor: pointer;
		background: #f0f0f0;
		color: #333333;
		font-weight: 600;
		display: flex;
		align-items: center;
		justify-content: center;
		min-width: 198rpx;

		.option-info {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			text-align: center;
		}

		.area-name {
			font-size: 28rpx;
			margin-bottom: 8rpx;
			margin-right: 10rpx;
		}

		.price-group {
			display: flex;
			align-items: center;
			gap: 10rpx;
		}

		.preferential-price {
			color: #2F80ED;
			font-size: 30rpx;
			font-weight: 600;
		}

		.original-price {
			color: #999;
			font-size: 20rpx;
			text-decoration: line-through;
		}
	}

	.option.active {
		background: #e6f0ff;
		color: #2f80ed;
		border: 1rpx solid #2f80ed;
	}

	/* 服务规格样式 */
	.section2 {
		margin-bottom: 30rpx;

		.section-title {
			font-weight: 400;
			color: #666;
			font-size: 30rpx;
		}
	}

	.options2 {
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;

	}

	.option2 {
		padding: 20rpx 35rpx;
		border-radius: 10rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		cursor: pointer;
		// height: 80rpx;
		background: #f0f0f0;
		color: #333333;
		font-weight: 600;
		display: flex;
		// align-items: center;
		justify-content: center;
		width: 100%;
		flex-direction: column;

		.option-box {
			display: flex;
			width: 100%;
			justify-content: space-between;
			align-items: center;
		}

		.ProductSpecification-box {
			margin-top: 10rpx;

			.ProductSpecification-text {
				font-weight: 400;
				font-size: 24rpx;
				color: #666;
			}
		}
	}

	.option2.active {
		background: #e6f0ff;
		// height: 80rpx;
		color: #2f80ed;
		border: 1rpx solid #2f80ed;
	}

	/* 推荐标签样式 */
	.recommended {
		width: 64rpx;
		height: 32rpx;
		margin-left: 20rpx;
	}

	/* 价格样式 */
	.price {
		color: #333333;
		font-weight: 600;
		font-size: 30rpx;
	}

	.active-price {
		color: #2F80ED;
	}

	/* 底部按钮样式 */
	.popup-footer {
		display: flex;
		justify-content: space-around;
		padding: 30rpx;
		margin-bottom: 30rpx;
	}

	.add-to-cart {
		width: 280rpx;
		height: 88rpx;
		background: #feb310;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 44rpx;
		border: none;
		font-size: 30rpx;
	}

	.order-now {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 280rpx;
		height: 88rpx;
		background: #2f80ed;
		color: white;
		border-radius: 44rpx;
		border: none;
		font-size: 30rpx;
	}
</style>